﻿using System;
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.Regions;
using Telerik.Windows.Controls;
using IActiveAware = Microsoft.Practices.Prism.IActiveAware;

namespace Infrastructure
{
    [Export]
    public class DockingRegionAdapter : RegionAdapterBase<RadDocking>
    {
        private IRegion _region;

        [ImportingConstructor]
        public DockingRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory, IRegionViewRegistry regionViewRegistry)
            : base(regionBehaviorFactory)
        {
            regionViewRegistry.ContentRegistered += OnContentRegistered;
        }

        protected override void Adapt(IRegion region, RadDocking regionTarget)
        {
            regionTarget.PanesSource = region.Views;
        }

        protected override IRegion CreateRegion()
        {
            _region = new Region();
            return _region;
        }

        public void OnContentRegistered(object sender, ViewRegisteredEventArgs e)
        {
            var view = e.GetView();
            if (view is IPaneModel && view is IActiveAware)
            {
                var activeAware = (IActiveAware) view;
                activeAware.IsActiveChanged += OnIsActiveChanged;
            }
        }

        private void OnIsActiveChanged(object sender, EventArgs eventArgs)
        {
            if (_region == null) return;

            var activeAware = (IActiveAware)sender;
            if (activeAware.IsActive) _region.Activate(activeAware);
            else _region.Deactivate(activeAware);
        }
    }
}